import React from 'react';
import Editor from '@monaco-editor/react';
import { renderMarkdown } from '../markdown-renderer';

const CODE_BLOCK_REGEX = /```(\w+)?\n([\s\S]*?)```/g;

interface RichContentProps {
  content: string;
  className?: string;
  monospaceHeight?: number;
}

export function RichContent({ content, className = '', monospaceHeight = 220 }: RichContentProps) {
  const segments = React.useMemo(() => {
    const parts: Array<{
      type: 'text' | 'code';
      language?: string;
      value: string;
    }> = [];

    let lastIndex = 0;
    let match: RegExpExecArray | null;

    while ((match = CODE_BLOCK_REGEX.exec(content)) !== null) {
      const [full, langRaw, codeRaw] = match;
      const matchStart = match.index;

      if (matchStart > lastIndex) {
        parts.push({ type: 'text', value: content.slice(lastIndex, matchStart) });
      }

      parts.push({
        type: 'code',
        language: langRaw?.trim() || 'plaintext',
        value: codeRaw || ''
      });

      lastIndex = matchStart + full.length;
    }

    if (lastIndex < content.length) {
      parts.push({ type: 'text', value: content.slice(lastIndex) });
    }

    return parts.length ? parts : [{ type: 'text', value: content }];
  }, [content]);

  if (!content?.trim()) {
    return <div className={`text-sm opacity-70 italic ${className}`}>暂无内容</div>;
  }

  return (
    <div className={`space-y-3 ${className}`}>
      {segments.map((segment, index) => {
        if (segment.type === 'code') {
          return (
            <div key={`code-${index}`} className="rounded-xl border border-white/20 bg-black/40 overflow-hidden">
              <Editor
                width="100%"
                height={monospaceHeight}
                theme="vs-dark"
                language={segment.language}
                value={segment.value.trim()}
                options={{
                  readOnly: true,
                  minimap: { enabled: false },
                  scrollBeyondLastLine: false,
                  wordWrap: 'on',
                  fontSize: 13,
                  lineNumbers: 'off'
                }}
              />
            </div>
          );
        }

        const html = renderMarkdown(segment.value);
        return (
          <div
            key={`text-${index}`}
            className="prose prose-invert max-w-none whitespace-pre-wrap leading-relaxed"
            dangerouslySetInnerHTML={{ __html: html }}
          />
        );
      })}
    </div>
  );
}
